package com.sujinyang.stateless_service.shiro;

import com.sujinyang.stateless_service.common.Constans;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class StatelessFilter extends AccessControlFilter {


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        //requrst中获取相应的username
        String username = request.getParameter(Constans.PARAM_USERNAME);
        //request中获取相应的密文
        String clinetDigest = request.getParameter(Constans.PARAM_DIGEST);
        //request中获取相应的参数,需要重新new一个map存放request里的map信息，因为request里的map是锁住不允许修改的
        Map<String,String[]> params = new HashMap<>(request.getParameterMap());
        params.remove(Constans.PARAM_DIGEST);
        StatelessToken token = new StatelessToken(username,params,clinetDigest);

        try {
            getSubject(request,response).login(token);
        }catch (Exception e) {
            e.printStackTrace();
            failLogin(response);
            return false;
        }

        return true;
    }

    private void failLogin(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("login failed");
    }
}
